import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { StorageService } from '../shared/services/storage.service';
import { Claims, HttpVerb } from '../shared/models/claims.model';

/**
 * Route guard. Validates route using claims
 * 
 * Author: Sorin Spiru, Andrei Istrate
 * Date: 13.01.2018
 */
@Injectable()
export class RouteGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot) {
        if (RouteGuard.canActivate(route.data['claim']))
            return true;

        this.router.navigate(['/']);
        return false;
    }

    public static canActivate(claim: Claims): boolean {
        let result: boolean = false;
        if (claim) {
            let permissions = StorageService.get().resourcePermissions;
            result = permissions.filter(x => x.resource.toLowerCase() == claim.resource.toLowerCase() && 
            x.verb.toString() == HttpVerb[claim.verb]).length > 0;
        }
        else
            result = true;
        return result;
    }
}